import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    list: [],
    inputValue: 'java',
    nextId: 4,
    itemKey: 'all'
  },
  mutations: {
    /* 初始化列表 */
    initList (state, list) {
      state.list = list
    },
    /* 双向数据绑定 */
    setInputValue (state, val) {
      state.inputValue = val
    },
    /* 添加列表项 */
    addItem (state) {
      const obj = {
        id: state.nextId,
        info: state.inputValue.trim(),
        done: false
      }
      state.list.push(obj)
      state.nextId++
      state.inputValue = ''
    },
    /* 删除列表项 */
    deleteItem (state, id) {
      /* 返回不等于当前id的 */
      state.list = state.list.filter((item) => item.id !== id)
    },
    /* 改变列表项状态 */
    changeStatus (state, param) {
      state.list.map((item, index) => {
        if (item.id === param.id) {
          state.list[index].done = param.status
        }
      })
    },
    /* 清除已完成列表 */
    clean (state) {
      state.list = state.list.filter(item => item.done === false)
    },
    switchItem (state, key) {
      state.itemKey = key
    },
    test () {
      console.log('3')
    },
    test2 () {
      console.log('5')
    }
  },
  actions: {
    /* 发起请求，初始化list列表 */
    getList (content) {
      axios.get('/list.json').then(({ data }) => {
        /* 触发mutations对象下的initList方法 并把data传过去 */
        content.commit('initList', data)
      })
    },
    test ({ commit }) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          commit('test')
          resolve('4')
        }, 3000)
      })
    },
    test2 ({ dispatch, commit }) {
      return dispatch('test').then(() => {
        commit('test2')
      })
    }
  },
  /* getters相当于组件的计算属性 */
  getters: {
    unDoneLength (state) {
      return state.list.filter(item => item.done === false).length
    },
    infoList (state) {
      if (state.itemKey === 'all') {
        return state.list
      }
      if (state.itemKey === 'done') {
        return state.list.filter(item => item.done === true)
      }
      if (state.itemKey === 'undone') {
        return state.list.filter(item => !item.done)
      }
      return state.list
    }
  },
  modules: {
  }
})
